<template>
	<div class="wrapper xinJian">
		<myhead activeIndex="/video"></myhead>
		<div class="content">
			<div class="content-item1">
				<div class="information">
					<h3>
						<el-icon style="margin-right: 5px"> <Connection /> </el-icon>基本信息
					</h3>
				</div>
				<div class="information-text">{{ titileName }}</div>
				<div class="information information-content">
					<el-form ref="formRef" :rules="rules" :model="form" label-width="100px">
						<el-form-item label="标题" prop="title" class="span-2">
							<el-input
								placeholder="请输入标题"
								v-model="form.title"
								class="width-item"
								:maxlength="255"
								style="width: 100%"
							/>
						</el-form-item>
						<el-form-item label="发布部门" prop="deptId" ref="elFormItemAuthRefs">
							<v-bumen
								v-model="form.deptId"
								:placeholder="'请选择部门'"
								:title="'选择部门'"
								:placeholders="'请输入部门进行搜索'"
								@close="onDeptClose"
								style="width: 100%"
							></v-bumen>
						</el-form-item>
						<el-form-item label="作者" prop="auth" ref="elFormItemAuthRef">
							<div>
								<v-department
									v-model="form.auth"
									:placeholder="'请选择作者'"
									:title="'选择作者'"
									:placeholders="'请输入用户名进行搜索'"
									@close="onAuthClose"
								></v-department>
							</div>
						</el-form-item>

						<el-form-item label="发布时间" prop="pubTime">
							<el-date-picker
								class="width-item"
								v-model="form.pubTime"
								type="date"
								placeholder="选择发布日期"
								value-format="YYYY-MM-DD"
								@blur="timeChange"
								:disabled-date="disabledDates"
								style="width: 100%"
							>
							</el-date-picker>
						</el-form-item>
						<el-form-item label="过期时间">
							<el-date-picker
								:disabled-date="disabledDate"
								class="width-item"
								v-model="form.expTime"
								type="date"
								placeholder="选择过期日期"
								value-format="YYYY-MM-DD 00:00:00"
								style="width: 100%"
							>
							</el-date-picker>
						</el-form-item>
						<el-form-item label="所属分类" prop="categoryId">
							<div>
								<el-select class="width-item" v-model="form.categoryId" placeholder="请选择分类">
									<el-option
										v-for="item in classification"
										:key="item.id"
										:label="item.name"
										:value="item.id"
									>
									</el-option>
								</el-select>
							</div>
							<!-- <el-input class="width-item"></el-input> -->
						</el-form-item>
						<el-form-item label="标签" class="no-inline">
							<v-select-tags v-model="form.label" :isShow="false">
								<template #tags="{ onOpenDialog, onDelete, selectedNames }">
									<div v-if="selectedNames.length">
										<el-tag v-for="(item, index) in selectedNames" class="mx-1">
											{{ item }}
										</el-tag>
										<el-button style="margin-left: 12px" type="primary" @click="onOpenDialog">
											编辑标签
										</el-button>
									</div>
									<el-input
										v-else
										type="text"
										placeholder="请选择标签"
										readonly
										@click="onOpenDialog"
										style="width: 100%"
									>
									</el-input>
								</template>
							</v-select-tags>
						</el-form-item>
						<el-form-item label="摘要" prop="remark" class="remarks no-inline">
							<div class="remark" style="width: 100%">
								<el-input
									placeholder="请输入摘要"
									v-model="form.remark"
									class="width-item"
									type="textarea"
									maxlength="500"
									@blur="remarkBlur"
									show-word-limit
									:autosize="{
										minRows: 5,
										maxRows: 10,
									}"
									style="width: 100%"
								/>
								<div class="remark-text" v-if="remarkIf">请输入摘要</div>
							</div>
						</el-form-item>
						<el-form-item label="视频上传" prop="videos" class="no-inline">
							<div class="uploads">
								<el-upload
									v-model="form.videos"
									:before-upload="beforeAvatarUploads"
									:http-request="upfiles"
									:show-file-list="true"
									drag
									action="/"
									multiple
									:limit="1"
									:file-list="form.videos"
									:on-progress="onProgress"
									class="v-upload-input"
									accept="video/*"
								>
									<template #file>
										<div v-for="(item, index) in form.videos" :key="index" class="upload-file">
											<div>
												{{ item.name }}
											</div>
											<span class="videoList" style="margin-left: auto" @click="dialogValue"
												><el-icon> <VideoPlay /> </el-icon
											></span>
											<span class="videoList" @click="delVideo(index)"
												><el-icon> <Close /> </el-icon
											></span>
										</div>
									</template>
									<!-- <el-button type="primary">点击上传附件</el-button> -->
									<el-icon class="el-icon--upload"><upload-filled /></el-icon>
									<div class="el-upload__text">
										<div style="color: #1a73e8">点击上传</div>
										<div>最多上传1个视频<br />最大不超过 1024 M</div>
									</div>
									<template #tip>
										<div class="el-upload__tip">请上传MP4格式的视频文件</div>
										<div class="el-upload__tip">最大支持1024M大小</div>
									</template>
								</el-upload>
								<div class="upload-progress" v-if="uploadNumber > 1">
									上传中...
									<el-progress :percentage="uploadNumber" />
								</div>
							</div>

							<video
								:src="form.videos && form.videos[0] ? form.videos[0].url : ''"
								id="upload-video-preview"
								crossorigin="anonymous"
								controls
								style="display: none"
							></video>
						</el-form-item>
						<el-form-item label="封面上传" prop="cover" class="no-inline">
							<el-upload
								class="avatar-uploader"
								action="/"
								:before-upload="beforeAvatarUpload"
								:on-change="onChangeUpload"
								:auto-upload="false"
								:show-file-list="false"
								ref="upload"
								accept="image/*"
							>
								<img v-if="form.cover" :src="form.cover" class="avatar" />
								<el-icon v-else class="avatar-uploader-icon">
									<Plus />
								</el-icon>
								<template #tip>
									<div class="el-upload__tip">
										系统默认选中视频第一帧为封面<br />支持上传jpg/png文件,<br />建议上传1335 x
										890的图片
									</div>
								</template>
							</el-upload>
							<VCropper
								ref="cropper"
								@success="handleAvatarSuccess"
								:size="5"
								:title="'封面'"
								:autoCropWidth="267"
								:autoCropHeight="178"
								:fixed="false"
								mode="270px 180px"
								:centerBox="false"
								:enlarge="5"
							></VCropper>
						</el-form-item>

						<!-- <el-form-item> -->
						<div class="form-bottom">
							<el-button @click="quxiao">取消</el-button>
							<el-button v-loading="loading" @click="submit('draft')" type="warning">保存草稿</el-button>
							<el-button v-loading="loading" type="primary" @click="submit('sub')">提交</el-button>
						</div>
						<!-- </el-form-item> -->
					</el-form>
				</div>
			</div>
			<el-dialog v-model="dialogVisible" title="观看视频" width="60%" :destroy-on-close="true">
				<video :src="form.videos[0].url" class="video" controls="controls">暂不支持</video>
			</el-dialog>
		</div>
		<v-myfoot></v-myfoot>
	</div>
</template>

<script setup>
import vSelectTags from "/packages/v-select-tags/index.vue"
import { Close, Plus, VideoPlay } from "@element-plus/icons-vue"
import VCropper from "../../components/cropper/index.vue"
import { ElMessage } from "element-plus"
import { useCutFirstVideoFrame } from "/plugins/video"
import { nextTick } from "vue"

const form = reactive({
	title: "", //标题
	auth: [], //作者
	deptId: [], //部门
	pubTime: "", //发布时间
	expTime: "", //过期时间
	label: [], //标签
	remark: "", //标签
	cover: "", //封面
	videos: [], //视频
	categoryId: "",
	modelId: "",
})

const videoFrame = ref("")

const remarkIf = ref(false)
const dialogVisible = ref(false)
let timer
const uploadNumber = ref(1)
const loading = ref(false)
const beforeAvatarUpload = rawFile => {
	if (rawFile.type !== "image/jpeg" && rawFile.type !== "image/png") {
		ElMessage.error("请上传png/jpeg格式文件")
		return false
	} else if (rawFile.size / 1024 / 1024 > 2) {
		ElMessage.error("图片大小不能超过2MB!")
		return false
	}
	return true
}
const beforeAvatarUploads = rawFile => {
	if (rawFile.type !== "video/mp4") {
		ElMessage.error("请上传mp4格式文件")
		return false
	} else if (rawFile.size / 1024 / 1024 > 1024) {
		ElMessage.error("视频大小不能超过1024MB!")
		return false
	}
	return true
}
//效验
const rules = reactive({
	title: [{ required: true, message: "请输入标题", trigger: "blur" }],
	auth: [{ required: true, message: "请选择作者", trigger: "change" }],
	deptId: [{ required: true, message: "请选择部门", trigger: "change" }],
	pubTime: [{ required: true, message: "请选择发布时间", trigger: "change" }],
	cover: [{ required: true, message: "请上传一个封面", trigger: "blur" }],
	videos: [{ required: true, message: "最少上传一个视频附件", trigger: "blur" }],
	categoryId: [{ required: true, message: "请选择分类", trigger: "blur" }],
	remark: [{ required: true, message: "请输入摘要", trigger: "blur" }],
})

//清空
function clean() {
	form.title = ""
	form.auth = []
	form.deptId = []
	form.pubTime = ""
	form.categoryId = ""
	form.expTime = ""
	form.label = []
	form.remark = ""
	form.cover = ""
	form.videos = []
}
const route = useRoute()
const titileName = ref("")
const router = useRouter()
//标签弹窗
const formRef = ref()
//分类
const tagList = ref({})
const classification = ref([])
async function cread() {
	if (route.query.name) {
		titileName.value = route.query.name
	}
	//动态渲染
	//用户标签
	tagList.value = await getAxios(`/knowledge/kbBasicLabel/list?bId=${route.query.id}`)
	const resAdd = await getAxios(`/knowledge/kbCategory/findBySwWidToBackstageAdd?swId=${route.query.swId}`)
	classification.value = resAdd
	if (route.query.id) {
		form.categoryId = route.query.id
	}

	if (route.query.edit == "2") {
		try {
			const res = await getAxios(`/knowledge/kbVideo/findByIdVideo?num=1&id=${route.query.id}`)
			titileName.value = res.subjectWarehouseName
			form.title = res.title
			form.auth[0] = {
				realName: res.authName,
				id: res.auth,
			}
			form.deptId[0] = {
				name: res.deptName,
				id: res.deptId,
			}
			form.pubTime = res.pubTime
			form.categoryId = res.categoryId
			form.expTime = res.expTime
			form.label = tagList.value || []
			form.remark = res.remark
			form.cover = res.cover
			form.videos = res.videoSrc || []
		} catch (error) {
			form.categoryId = ""
			ElMessage.error(error)
		}
	} else {
		const userInfo = JSON.parse(localStorage.getItem("userInfo"))
		form.auth[0] = {
			realName: userInfo.realName,
			id: userInfo.id,
		}
		form.deptId[0] = {
			name: userInfo.deptName,
			id: userInfo.deptId,
		}
	}
}
cread()

const elFormItemAuthRef = ref()
const elFormItemAuthRefs = ref()

function onAuthClose() {
	elFormItemAuthRef.value.clearValidate()
}
function onDeptClose() {
	elFormItemAuthRefs.value.clearValidate()
}
const upfiles = async params => {
	params.onProgress(onProgress)
	form.videos = []
	const file = params.file
	const formData = new FormData()
	formData.append("upfile", file)
	const res = await postAxios("/system/oss/upload", formData)
	form.videos = [res]
	if (form.title == "") {
		form.title = form.videos[0].name.substr(0, form.videos[0].name.lastIndexOf("."))
	}
	uploadNumber.value = 0
	clearInterval(timer)

	await nextTick()

	if (!form.cover) {
		const [result] = await useCutFirstVideoFrame("#upload-video-preview")

		let coverFormData = new FormData()
		let fileName = params.file.name.split(".")
		fileName.pop()

		coverFormData.append(
			"upfile",
			new File(
				[result], // 将Blob类型转化成File类型
				[fileName, "png"].join("."), // 设置File类型的文件名称
				{ type: "image/png" } // 设置File类型的文件类型
			)
		)
		try {
			const { url } = await postAxios("/system/oss/upload", coverFormData)

			form.cover = url
		} catch (error) {
			console.log(error)
		}
	}
}

const onProgress = () => {
	uploadNumber.value = 1
	timer = setInterval(() => {
		if (uploadNumber.value == 0) {
			clearInterval(timer)
			return
		}
		uploadNumber.value += (Math.random() * (100 - uploadNumber.value)) / 10
	}, 400)
}
//视频删除
const delVideo = index => {
	form.videos.splice(index, 1)
}
const fabu = ref(false)
//提交
const submit = async item => {
	loading.value = true
	if (form.remark == "") {
		remarkIf.value = true
	} else {
		remarkIf.value = false
	}
	if (fabu.value) {
		return
	} else {
		fabu.value = true
		try {
			await formRef.value.validate()
			let src = {}
			src.title = form.title
			src.auth = form.auth[0].id
			src.deptId = form.deptId[0].id
			src.pubTime = form.pubTime
			src.expTime = form.expTime
			// src.label = form.label
			src.cover = form.cover
			src.videoSrc = form.videos
			src.categoryId = form.categoryId
			src.remark = form.remark
			let listLabel = []
			form.label.forEach(items => {
				listLabel.push({
					name: items.name,
					status: items.status,
				})
			})
			src.labels = listLabel
			if (item == "sub") {
				if (route.query.edit == 2) {
					try {
						src.id = route.query.id
						src.status = 1
						await postAxios("/knowledge/kbVideo/edit", src)
						ElMessage.success("修改成功")
						loading.value = false
						router.back()
						clean()
					} catch (error) {
						ElMessage.error(error)
						loading.value = true
					}
				} else {
					try {
						src.status = 1
						await postAxios("/knowledge/kbVideo/save", src)
						ElMessage.success("保存成功")
						loading.value = false
						router.back()
						clean()
					} catch (error) {
						ElMessage.error(error)
						loading.value = true
					}
				}
			} else {
				try {
					src.id = route.query.id
					src.status = 2
					await postAxios("/knowledge/kbVideo/edit", src)
					ElMessage.success("保存草稿成功")
					loading.value = false
					router.back()
					clean()
				} catch (error) {
					ElMessage.error(error)
					loading.value = true
					fabu.value = false
				}
			}
		} catch (error) {
			fabu.value = false
			ElMessage.error("请输入必填项")
			loading.value = false
		}
	}
}
const disabledDate = time => {
	let timeS = new Date(form.pubTime).getTime()
	return time.getTime() < new Date(form.pubTime).getTime()
}
function addZero(s) {
	return s < 10 ? "0" + s : s
}
const timeChange = () => {
	let date = new Date()
	form.pubTime =
		form.pubTime +
		" " +
		addZero(date.getHours()) +
		":" +
		addZero(date.getMinutes()) +
		":" +
		addZero(date.getSeconds())
}
const quxiao = () => {
	if (route.query.edit == 2) {
		router.push(`/videoDetails?id=${route.query.id}&swId=${route.query.swId}`)
	} else {
		router.go(-1)
	}
}
const dialogValue = () => {
	dialogVisible.value = true
}
const remarkBlur = () => {
	if (form.remark == "") {
		remarkIf.value = true
	} else {
		remarkIf.value = false
	}
}

const upload = ref("")
const cropper = ref("")

// 图片裁剪
function onChangeUpload(file) {
	cropper.value.handleChangeUpload(file)
	upload.value.clearFiles()
}

//上传成功
const handleAvatarSuccess = res => {
	form.cover = res.url
}
function disabledDates(time) {
	return time.getTime() < Date.now() - 8.64e7
}
</script>
<style lang="scss" scoped>
@import "/style/basis";

.xinJian {
	background-color: #f8f8f8;

	.content {
		width: 100%;
		padding: 25px 50px;
		height: 80vh;
		background-color: #f8f8f8;
		border-radius: 10px;
		display: flex;

		@include maxWidth(450) {
			padding: 5px 0px;
		}

		.content-item1 {
			text-align: center;

			background-color: #fff;
			width: 100%;
			height: 100%;
			padding: 20px 40px;
			// border-right: 3px solid #ccc;
			overflow: auto;
			@include maxWidth(660) {
				padding: 20px 0;
			}
			.information {
				margin: 20px 0;
			}

			.information-content {
				display: flex;
				padding: 0 10vw;
				justify-content: center;
				:deep(form) {
					display: flex;
					flex-wrap: wrap;
					justify-content: space-between;
					.el-form-item {
						width: 33%;
						@include maxWidth(1500) {
							width: 50%;
						}
						@include maxWidth(1070) {
							width: 51%;
							display: flex;
							justify-content: center;
						}
						.el-form-item__content {
							align-items: baseline;
						}

						&.span-2 {
							width: 66.6666%;
						}
						&.no-inline {
							width: 100%;
						}
					}
					@include maxWidth(1070) {
						justify-content: space-between;
					}
				}
				.form-bottom {
					margin-top: 50px;
					width: 100%;
					bottom: 20px;
				}
				@include maxWidth(569) {
					padding: 0;
				}
				:deep(.el-upload) {
					border: 1px dashed #999;
				}
			}

			.information-text {
				margin-bottom: 40px;
			}
		}

		.content-item1::-webkit-scrollbar {
			overflow: -moz-hidden-unscrollable;
		}
	}

	::v-deep .el-input-group__append {
		background-color: #2972fa;
		color: #fff;
		box-shadow: 0 0 0;
	}

	.el-checkbox-button {
		margin: 10px;
	}

	::v-deep.el-checkbox-button__inner {
		border: 0 !important;
	}

	.el-upload__tip {
		margin-left: 10px;
	}

	.el-scrollbar {
		display: none;
	}

	.bq {
		padding: 10px 20px;
		text-align: center;
		margin: 10px 20px;
		border-radius: 30px;
		cursor: pointer;
		background-color: #f4f4f4;
	}

	.label-item {
		margin-top: 20px;
		padding: 20px 40px;
		border-top: 1px solid #2972fa;
		border-bottom: 1px solid #2972fa;
		display: flex;
		justify-content: space-between;
		line-height: 2;
	}

	.checkbox {
		margin: 20px 0;
		display: flex;
		justify-content: space-between;
	}

	.operate {
		margin-top: 20px;
		display: flex;
		justify-content: flex-end;
	}

	.selectColor {
		background-color: #2972fa;
	}

	.avatar-uploader {
		width: 256px;
		height: 165px;
		display: block;
	}

	.avatar-uploader .avatar {
		width: 256px;
		height: 165px;
		display: block;
	}

	.avatar-uploader .el-upload {
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		// transition: var(--el-transition-duration-fast);
	}

	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}

	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 256px;
		height: 165px;
		text-align: center;
	}

	.selectDel {
		cursor: pointer;
		margin-left: 15px;
		width: 75px;
	}

	.videoList {
		margin-left: 15px;
		font-size: 18px;
		cursor: pointer;
	}
}

.width-item {
	width: 250px;

	@include maxWidth(450) {
		width: 200px;
	}
}

:deep(.el-date-editor.el-input) {
	width: 250px;

	@include maxWidth(450) {
		width: 200px;
	}
}

.width-item-label {
	// width: 400px;
	text-align: left;

	@include maxWidth(768) {
		width: 250px;
	}

	.mx-1 {
		margin-right: 10px;
	}
}
.remarks {
	.remark {
		position: relative;
		margin-bottom: 10px;
		.remark-text {
			position: absolute;
			font-size: 12px;
			color: #f56c6c;
			bottom: -10;
			left: 0;
		}
	}
	:deep(.el-form-item__error) {
		display: none;
	}
}
.uploads {
	display: flex;
	flex-direction: column;
	.v-upload-input {
		min-width: 250px;
		border-radius: 20px;
		border-radius: 10px !important;
		:deep(.el-upload-dragger) {
			padding: 20px;
			border: 0;
		}

		.upload-file {
			display: flex;
			justify-content: flex-start;
			align-items: center;
		}
	}
	:deep(.el-progress__text) {
		display: none;
	}
}
.video {
	width: 100%;
	height: 100%;
}
:deep(.el-dialog) {
	min-width: 400px !important;
}
</style>
